<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-document-copy" size="mini" @click="exporFormVisible = true">设备管控锁</el-button>
        <el-button type="primary" size="mini" @click="handleDownload">下载导入模板<i class="el-icon-paperclip el-icon--right"></i></el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="SN码" value="1"></el-option>
              <el-option label="归属" value="3"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" min-width="130" align="center" prop="username" label="sn码归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="130" align="center" prop="value" label="SN码"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="130" align="center" prop="is_lock" label="设备状态">
        <template slot-scope="scope">{{scope.row.is_lock ? '锁定' : '解锁'}}</template>
      </el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="130" align="center" prop="is_lock" label="解除封闭时间">
        <template slot-scope="scope">{{scope.row.is_lock_time | newDate}}</template>
      </el-table-column>
      <el-table-column min-width="100" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" @click="getdeleteLabel(scope.row)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- SN码解锁 -->
    <el-dialog title="设备管控" :visible.sync="exporFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="exporForm" :rules="rules" ref="ruleForm">
        <el-form-item label="设备管控:" label-width="130px">
          <el-radio-group v-model="exporForm.type">
            <el-radio label="1">解锁设备</el-radio>
            <el-radio v-permission="['超级管理员','管理员']" label="2">锁定设备</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类型:" label-width="130px">
          <el-radio-group v-model="exporFormType">
            <el-radio label="1">单条</el-radio>
            <el-radio label="2">多条</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="typeShow">
          <el-form-item label="SN" label-width="100px" prop="sn">
            <el-input v-model="exporForm.sn" class="add_select" placeholder="请输入SN" :maxlength="12"></el-input>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="导入文件" label-width="130px" class="snElsx">
            <div class="">
              <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="exporForm.file.name"></el-input>
              <upload-excel-component class="flex mrg-top" :before-upload="batchUpload" @submitXlsx="submitXlsx" :loading="!videoFlag">
                <span>{{videoFlag ? '' : goodsData + '%'}}</span>
              </upload-excel-component>
            </div>
          </el-form-item>
          <div v-if="batchShow">
            <el-form-item label="成功导入:" label-width="130px" style="margin-bottom:0">共{{ this.snData.succeed}}条</el-form-item>
            <el-form-item label="导入失败:" label-width="130px" style="margin-bottom:0"> 共{{ this.snData.fail.length}}条</el-form-item>
            <el-form-item label="相同的SN:" label-width="130px" style="margin-bottom:0"> 共{{ this.snData.sameData}}条
              {{ this.snData.same.length >= 1 ? `( 位于:第${this.snData.same.toString()}行 ), 只展示前10行` : ''}}
            </el-form-item>
            <el-form-item label="总条数:" label-width="130px" style="margin-bottom:0">共{{snData.all}}条</el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exporFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="uploadButton" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import UploadExcelComponent from "@/components/UploadExcelSn/index.vue";
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { appLockList, queryPAD, importPAD, singleSn, queryPADBaYi, importPADBaYi, singleSnBaYi } from "@/api/lock.js";
import permission from '@/directive/permission/index.js' // 权限判断指令
import { mapState } from 'vuex'
import deleteDialog from "@/components/deleteDialog";
export default {
  components: { UploadExcelComponent, dynamicTable, deleteDialog },
  directives: { permission },
  data() {
    return {
      checkboxVal: ["sn码归属", "SN码", "设备状态", "解除封闭时间"],
      key: 1,
      colData: [], //动态控制table
      //归属table
      browserTable: [],
      total: 0,
      searchTable: "",
      select: "", //搜索条件
      exporFormVisible: false,
      exporForm: { type: '1', file: {}, sn: '' },
      rules: { name: [{ required: true, message: "导入文件不能为空", trigger: "blur" }] },
      batchShow: false,
      //上传后显示的数据
      snData: { same: [], sameData: 0, fail: [], succeed: '', all: '' },
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), sn: undefined, username: undefined, batch: undefined, sort: '' },
      videoFlag: true,
      exporFormType: '1',
      deleteDialogs: { show: false, deleteText: '', deleteId: 0, sn: '' },
    }
  },
  computed: {
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    }),
    typeShow() {
      return this.exporFormType == 1 ? true : false
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getqueryPADBaYi()
  },
  methods: {
    //删除
    getdeleteLabel(row) {
      this.deleteDialogs.show = true
      this.deleteDialogs.sn = row.value
    },
    //删除按钮事件
    deleteEvents() {
      this.getsingleSnBaYi(2, this.deleteDialogs.sn)
    },
    submitXlsx() {
      var fd = new FormData()
      fd.append('file', this.exporForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('type', this.exporForm.type)
      this.videoFlag = false
      importPADBaYi(fd).then(res => {
        this.batchShow = true
        this.snData.sameData = res.data[0].length
        this.snData.same = JSON.parse(JSON.stringify(res.data[0].splice(0, 10)))
        this.snData.fail = res.data[2]
        this.snData.succeed = res.data.excelSuccess
        this.snData.all = res.data.total
        this.$message.success(res.msg)
        this.videoFlag = true
        this.getqueryPADBaYi()
      }).catch(err => { })
    },
    batchUpload(file) {
      this.exporForm.file = file
    },
    getqueryPADBaYi() {
      queryPADBaYi(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
      }).catch(err => {
        this.browserTable = []
        this.total = 0
      });
    },
    //导入确定事件
    uploadButton() {
      if (this.exporFormType == 2) {
        if (this.exporForm.file instanceof File) {
          if (this.batchShow) {
            this.exporFormVisible = false
          } else {
            this.$message('存在导入文件未上传，请确认是否需要上传。')
          }
        } else {
          this.exporFormVisible = false
        }
      } else {
        this.getsingleSnBaYi()
      }
    },
    getsingleSnBaYi(type = this.exporForm.type, sn = this.exporForm.sn) {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), type: type, sn: sn }
      singleSnBaYi(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryPADBaYi()
        this.exporFormVisible = false
      }).catch(err => { })
    },
    //搜索,1:sn码,2,归属
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.sn = this.searchTable
          this.getqueryPADBaYi();
          break;
        case '2':
          this.listQuery.batch = this.searchTable
          this.getqueryPADBaYi();
          break;
        case '3':
          this.listQuery.username = this.searchTable
          this.getqueryPADBaYi();
          break;
      }
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryPADBaYi();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryPADBaYi();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), sn: undefined, username: undefined, batch: undefined, sort: '' }
      this.getqueryPADBaYi()
    },
    //导入模板
    handleDownload() {
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["SN码"];
        const filterVal = ["sn"];
        const list = [{ "sn": 'QNS2HIYS0003' }]
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({ header: tHeader, data, filename: '下载导入模板' });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    addFormclose() {
      this.$nextTick(() => {
        this.exporForm = { type: '1', file: {}, sn: '' }
        this.batchShow = false,
          this.exporFormType = '1'
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>